ENT.Type = "point"
ENT.SpawnedNPCs = {}
ENT.MobID = 0
ENT.SpawnRate = 1
ENT.SpawnedTotal = 0
ENT.SpawnedMax = 5
ENT.MaxTotal = 0
ENT.MaxLimited = false
ENT.Started = false
ENT.NextSpawn = 0
ENT.Radius = 0
ENT.AggroRadius = 1024
ENT.Wanderers = false

function ENT:Initialize()
	print("NPC Spawner created.")
end

function ENT:Think()
	for k, v in pairs(self.SpawnedNPCs) do
		if(!v or v:Health() <= 0)then
			table.remove(self.SpawnedNPCs, k)
			self.SpawnedTotal = self.SpawnedTotal - 1
		end
	end
	if(self.Started and self.NextSpawn < CurTime() and self.SpawnedTotal < self.SpawnedMax )then
		self:SpawnSafe()
		self.NextSpawn = CurTime() + self.SpawnRate
	end
end

function ENT:SpawnSafe()
	local entsphere = ents.FindInSphere(self:GetPos(), 32)
	if(#entsphere > 0)then
		for k, v in pairs(entsphere)do
			if(v:GetClass() == "npc_rpgdm")then
				return false
			else
			end
		end
	end
	local npc = CreateNPC(self.MobID, self:GetPos())
	if(type(npc) == "NextBot")then
		npc.AggroRadius = self.AggroRadius
		npc.Wander = self.Wanderers
		table.insert(self.SpawnedNPCs, npc)
		self.SpawnedTotal = self.SpawnedTotal + 1
		if(self.MaxLimited and self.SpawnedTotal >= self.MaxTotal)then
			self:Remove()
		end
	end
end

function ENT:KeyValue(key, value)
	if(key == "targetname")then
		self:SetName(value)
	end
	if(key == "aggroradius")then
		self.AggroRadius = value
	end
	if(key == "parent")then
		self:SetParent(ents.FindByName(value)[1])
	end
	if(key == "spawnrate")then
		self.SpawnRate = tonumber(value)
	end
	if(key == "maxtotal")then
		self.MaxTotal = tonumber(value)
	end
	if(key == "spawnmax")then
		self.SpawnedMax = tonumber(value)
	end
	if(key == "mobid")then
		self.MobID = tonumber(value)
	end
	if(key == "startactive")then
		if(tonumber(value) == 1)then
			self.Started = true
		end
	end
	if(key == "wander")then
		if(tonumber(value) == 1)then
			self.Wanderers = true
		end
	end
	if(key == "limitedspawn")then
		if(value == 1)then
			self.MaxLimited = true
		end
	end
end

function ENT:AcceptInput( name, activator, caller, data )
	if (name == "Start") then 
		self.Started = true
    end
	if (name == "Stop") then 
		self.Started = false
    end
    if (name == "Spawn") then 
		self:SpawnSafe()
    end
	if (name == "SetMob") then 
		self.MobID = tonumber(data)
    end
	if (name == "KillAll") then
		for k, v in pairs(self.SpawnedNPCs) do
			v:SetHealth(0)
			table.remove(self.SpawnedNPCs, k)
		end
	end
end



